package com.miyouke.chat.listener;

import com.miyouke.chat.dto.AppControlDTO;
import com.miyouke.chat.entity.AppControl;
import com.miyouke.chat.service.AppControlService;
import com.miyouke.chat.util.BeanUtil;
import com.miyouke.chat.util.SshUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhr 2019/2/22
 */
@Component
@Slf4j
public class SShSessionListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private AppControlService appControlService;

    private Map<AppControlDTO, SshUtil> map = new HashMap<>();

    public SshUtil getSessionMap( AppControlDTO appControlDTO ){

        SshUtil sshUtil = map.get(appControlDTO);
        if( sshUtil == null ){
            sshUtil = createSSh(appControlDTO);
        }else{
            sshUtil.close();
            sshUtil = createSSh(appControlDTO);
        }
        return sshUtil;
    }

    private SshUtil createSSh(AppControlDTO appControlDTO) {
        try{
            SshUtil sshUtil = SshUtil.newInstance(appControlDTO.getUserName(), appControlDTO.getPassword(), appControlDTO.getHost(), appControlDTO.getPort());
            if(sshUtil.getSession() == null
                    || sshUtil.getSession().isConnected() == false){
                return null;
            }
            map.put(appControlDTO,sshUtil);
            return sshUtil;
        }catch (Exception e){
            log.error( "创建SSH失败:" , e);
        }
        return null;
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        // 1. 查询出所有的数据
        /*List<AppControl> list = appControlService.list();
        List<AppControlDTO> lists = list.stream()
                .map(appControl -> BeanUtil.transform(AppControlDTO.class, appControl))
                .distinct().collect(Collectors.toList());

        for (int i = 0; i <lists.size(); i++) {
            AppControlDTO appControlDTO = lists.get(i);
            SshUtil sshUtil = SshUtil.newInstance(appControlDTO.getUserName(), appControlDTO.getPassword(), appControlDTO.getHost(), appControlDTO.getPort());
            map.put(appControlDTO, sshUtil);
        }*/

    }


    /**
     * 每5分钟执行一次提交
     */
    @Scheduled(cron = "0 0/5 * * * *")
    public void saveTask() {
        // 查看Map中是否有连接已经断开
        Set<AppControlDTO> appControlDTOS = map.keySet();
        appControlDTOS.stream().forEach( key ->{
            SshUtil sshUtil = map.get(key);
            if(sshUtil.getSession().isConnected() == false){
                sshUtil.close();
                try{
                    SshUtil newSsh = SshUtil.newInstance(key.getUserName(), key.getPassword(), key.getHost(), key.getPort());
                    map.put(key, newSsh);
                }catch (Exception e){
                    map.remove(key);
                    log.error("ssh 连接异常："+key.toString(), e);
                }
            }
        });
    }

}
